// H5页面中用于与小程序通信的脚本

// 解析URL参数
function getUrlParams() {
  const params = {};
  const search = window.location.search.substring(1);
  if (!search) return params;
  
  search.split('&').forEach(pair => {
    const [key, value] = pair.split('=');
    if (key && value) {
      params[key] = decodeURIComponent(value);
    }
  });
  
  return params;
}

// 初始化 - 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  // 获取小程序传递的参数
  const params = getUrlParams();
  console.log('从微信小程序接收的参数:', params);

  //从微信小程序接收的参数: {"platform": "wechat_miniprogram", "timestamp": "1760014958272", "uid": "007630", "nickname": "15011007630"}
  var platform = params.platform;
  var timestamp = params.timestamp;
  var uid = params.uid;
  var nickname = params.nickname;


  if(nickname == null || nickname == undefined || nickname == ''){
     return;
  }

  $.ajax({
    type : "post",
    url : '/app/loginV1',
    contentType:'application/json;charset=utf-8',
    dataType : "json",
    data : JSON.stringify({
      username: nickname,
      password: uid
    }),
    async : true,
    success : function(json){
      if(json.code == 0){
        var user = json.user;
        var userId = json.user.userId;
        debugger
        console.log('使用从微信小程序接收的参数登录成功:', params);

        localStorage.setItem('password', password);
        localStorage.setItem("user", user);
        localStorage.setItem("userId", userId);
        localStorage.setItem("username", user.username);




        if(userId === 1){
          console.log('使用从微信小程序接收的参数登录成功:', '/app/adminindex');

          H.openWin('table_head', '/app/adminindex');
        }else{
          console.log('使用从微信小程序接收的参数登录成功:', '/app/merchantindex');
          H.openWin('table_head', '/app/merchantindex');
        }
      }else{
        alert(json.msg);
      }
    },
  });




  // 显示接收的参数
  displayParams(params);
  
  // 监听小程序发送的消息
  window.addEventListener('message', function(e) {
    // 验证消息来源，确保是从小程序发送的
    if (e.source === window && e.data && e.data.type) {
      console.log('H5收到小程序消息:', e.data);
      handleMiniProgramMessage(e.data);
    }
  });
  
  // 绑定按钮事件
  bindEvents();
});

// 显示参数到页面
function displayParams(params) {
  const paramsContainer = document.getElementById('params-container');
  if (paramsContainer) {
    let html = '<h3>从微信小程序接收的参数:</h3>';
    if (Object.keys(params).length > 0) {
      html += '<ul>';
      Object.keys(params).forEach(key => {
        html += `<li><strong>${key}:</strong> ${params[key]}</li>`;
      });
      html += '</ul>';
    } else {
      html += '<p>未接收到参数</p>';
    }
    paramsContainer.innerHTML = html;
  }
}

// 处理小程序发送的消息
function handleMiniProgramMessage(message) {
  const messageContainer = document.getElementById('message-container');
  if (!messageContainer) return;
  
  // 添加消息到显示区域
  const messageEl = document.createElement('div');
  messageEl.className = 'message-item from-miniprogram';
  messageEl.innerHTML = `
    <div class="message-time">${new Date(message.timestamp).toLocaleString()}</div>
    <div class="message-content">${JSON.stringify(message)}</div>
  `;
  messageContainer.prepend(messageEl);
  
  // 根据消息类型处理
  switch(message.type) {
    case 'storeSuccess':
      showToast(message.message || '数据存储成功');
      break;
    case 'storedData':
      displayStoredData(message.data);
      break;
  }
}

// 绑定页面事件
function bindEvents() {
  // 发送数据到小程序并存储
  document.getElementById('store-data-btn')?.addEventListener('click', function() {
    const data = {
      username: document.getElementById('username-input')?.value || '访客',
      email: document.getElementById('email-input')?.value || '',
      preferences: {
        theme: 'light',
        notifications: true,
        updatedAt: new Date().toISOString()
      }
    };
    
    sendToMiniProgram({
      type: 'storeData',
      data: data
    });
  });
  
  // 获取存储的数据
  document.getElementById('get-data-btn')?.addEventListener('click', function() {
    const key = document.getElementById('data-key-input')?.value || 'all';
    sendToMiniProgram({
      type: 'getStoredData',
      key: key
    });
  });
  
  // 发送提示消息
  document.getElementById('show-toast-btn')?.addEventListener('click', function() {
    const message = document.getElementById('toast-message')?.value || '来自H5的消息';
    sendToMiniProgram({
      type: 'showToast',
      content: message,
      icon: 'none',
      duration: 3000
    });
  });
  
  // 更新用户信息
  document.getElementById('update-user-btn')?.addEventListener('click', function() {
    const newNick = document.getElementById('new-nickname')?.value;
    if (newNick) {
      sendToMiniProgram({
        type: 'updateUserInfo',
        data: {
          nickName: newNick
        }
      });
    }
  });
}

// 发送消息到小程序
function sendToMiniProgram(message) {
  if (typeof wx !== 'undefined' && wx.miniProgram) {
    // 使用微信提供的postMessage方法
    wx.miniProgram.postMessage({
      data: message
    });
    
    // 显示发送成功的提示
    //alert('消息已发送到小程序');
    console.log('消息已发送到小程序');
    // 记录发送的消息
    const messageContainer = document.getElementById('message-container');
    if (messageContainer) {
      const messageEl = document.createElement('div');
      messageEl.className = 'message-item to-miniprogram';
      messageEl.innerHTML = `
        <div class="message-time">${new Date().toLocaleString()}</div>
        <div class="message-content">${JSON.stringify(message)}</div>
      `;
      messageContainer.prepend(messageEl);
    }
  } else {
    alert('未检测到小程序环境', 'error');
    console.error('当前不在微信小程序环境中');
  }
}

// 显示提示消息
function showToast(message, type = 'success') {
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.textContent = message;
  document.body.appendChild(toast);
  
  // 3秒后移除提示
  setTimeout(() => {
    toast.classList.add('fade-out');
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 300);
  }, 3000);
}

// 显示存储的数据
function displayStoredData(data) {
  const dataContainer = document.getElementById('stored-data-container');
  if (dataContainer) {
    if (data) {
      dataContainer.innerHTML = `
        <h3>从微信小程序获取的存储数据:</h3>
        <pre>${JSON.stringify(data, null, 2)}</pre>
      `;
    } else {
      dataContainer.innerHTML = '<h3>未找到对应的数据</h3>';
    }
  }
}
    